from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
from dhm.models.user.consumer import Consumer
import re

class Register(APIView):
    def post(self, request):
        data = request.POST
        username = data.get('username', '').strip()
        password = data.get('password', '').strip()
        # photo = data.get('data', '')
        phone_number = data.get('phone_number', '')
        consumer_address = data.get('consumer_address', '')
        password_confirm = data.get('password_confirm', '').strip()
        """
        if len(username) <= 6:
            return Response(
                'result': "用户名需大于6位"
            })
        if len(password) <= 8:
            return Response({
                'result': "密码至少需要为八位"
            })
        if not re.fullmatch(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', phone_number):
            return Response({
                'result': "请输入正确的邮箱格式"
            })
        """
        if not username or not password:
            return Response({
                'result': "用户名或密码不正确"
            })
        if not phone_number or not consumer_address:
            return Response({
                'result': "请将信息填写完整"
            })
        if password != password_confirm:
            return Response({
                'result': "两次密码不一致"
            })
        if User.objects.filter(username = username).exists():
            return Response({
                'result': "用户名已存在"
            })

        user = User(username=username)
        user.set_password(password)
        user.save()
        Consumer.objects.create(user=user, photo="https://pics7.baidu.com/feed/bf096b63f6246b608ed67b63fc8ca945500fa24f.jpeg?token=cfa3819ae882d3ad33e876f48ebf6c1b", username=username, phone_number=phone_number, consumer_address=consumer_address)
        print("注册成功！")
        return Response({
            'result': "success",
        })
